<template>
  <view class="page">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 用户信息头部 -->
    <view class="user-header">
      <view class="user-info">
        <image 
          class="avatar" 
          :src="userAvatar" 
          mode="aspectFill"
          @click="handleAvatarClick"
        />
        <view class="user-details">
          <view class="nickname">{{ userNickname }}</view>
          <view class="username">{{ userUsername }}</view>
        </view>
      </view>
      <view class="user-stats">
        <view class="stat-item">
          <text class="stat-value">{{ userStore.profile?.id || '--' }}</text>
          <text class="stat-label">用户ID</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ formatDate(joinDate) }}</text>
          <text class="stat-label">加入时间</text>
        </view>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-section">
      <view 
        class="menu-item" 
        v-for="menu in menuList" 
        :key="menu.id"
        @click="handleMenuClick(menu)"
      >
        <view class="menu-icon">{{ menu.icon }}</view>
        <view class="menu-content">
          <text class="menu-title">{{ menu.title }}</text>
          <text class="menu-desc" v-if="menu.desc">{{ menu.desc }}</text>
        </view>
        <view class="menu-arrow">></view>
      </view>
    </view>

    <!-- 设置选项 -->
    <view class="settings-section">
      <view class="section-title">设置</view>
      <view 
        class="setting-item" 
        v-for="setting in settingList" 
        :key="setting.id"
        @click="handleSettingClick(setting)"
      >
        <view class="setting-icon">{{ setting.icon }}</view>
        <view class="setting-content">
          <text class="setting-title">{{ setting.title }}</text>
          <text class="setting-value" v-if="setting.value">{{ setting.value }}</text>
        </view>
        <switch 
          v-if="setting.type === 'switch'" 
          :checked="setting.checked" 
          @change="handleSwitchChange(setting, $event)"
        />
        <view v-else class="setting-arrow">></view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-section">
      <button class="action-button" @click="handleLogout" v-if="userStore.isLoggedIn">
        退出登录
      </button>
      <button class="action-button primary" @click="handleLogin" v-else>
        立即登录
      </button>
    </view>

    <!-- 底部安全区域 -->
    <view class="safe-area-bottom"></view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useAppStore } from '../../store/app'
import { useUserStore } from '../../store/user'
import { formatDate, showToast, showConfirm, navigateTo } from '../../utils/common'

const appStore = useAppStore()
const userStore = useUserStore()

// 状态栏高度
const statusBarHeight = computed(() => appStore.systemInfo?.statusBarHeight || 0)

// 用户信息
const userAvatar = computed(() => 
  userStore.profile?.avatar || 'https://via.placeholder.com/80x80?text=头像'
)

const userNickname = computed(() => 
  userStore.profile?.nickname || userStore.profile?.username || '未登录'
)

const userUsername = computed(() => 
  userStore.profile?.username || '点击登录'
)

const joinDate = computed(() => 
  userStore.profile?.createTime || new Date().toISOString()
)

// 功能菜单
const menuList = ref([
  {
    id: 1,
    title: '个人资料',
    desc: '编辑个人信息',
    icon: '👤',
    path: '/pages/profile/profile'
  },
  {
    id: 2,
    title: '我的收藏',
    desc: '查看收藏内容',
    icon: '⭐',
    path: '/pages/favorites/favorites'
  },
  {
    id: 3,
    title: '消息通知',
    desc: '查看系统消息',
    icon: '🔔',
    path: '/pages/messages/messages'
  },
  {
    id: 4,
    title: '意见反馈',
    desc: '帮助我们改进',
    icon: '💬',
    path: '/pages/feedback/feedback'
  }
])

// 设置选项
const settingList = ref([
  {
    id: 1,
    title: '深色模式',
    icon: '🌙',
    type: 'switch',
    checked: appStore.theme === 'dark'
  },
  {
    id: 2,
    title: '语言设置',
    icon: '🌐',
    value: appStore.locale === 'zh-CN' ? '简体中文' : 'English',
    type: 'select'
  },
  {
    id: 3,
    title: '清除缓存',
    icon: '🗑️',
    type: 'action'
  },
  {
    id: 4,
    title: '关于应用',
    icon: 'ℹ️',
    value: `v${appStore.appVersion}`,
    type: 'page'
  }
])

// 处理头像点击
const handleAvatarClick = () => {
  if (!userStore.isLoggedIn) {
    handleLogin()
    return
  }
  
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const filePath = res.tempFilePaths[0]
      uploadAvatar(filePath)
    }
  })
}

// 上传头像
const uploadAvatar = async (filePath: string) => {
  try {
    await userStore.uploadAvatar(filePath)
    showToast('头像上传成功', 'success')
  } catch (error) {
    showToast('头像上传失败')
  }
}

// 处理菜单点击
const handleMenuClick = (menu: any) => {
  if (!userStore.isLoggedIn) {
    handleLogin()
    return
  }
  
  if (menu.path) {
    navigateTo(menu.path)
  } else {
    showToast(`点击了: ${menu.title}`)
  }
}

// 处理设置点击
const handleSettingClick = (setting: any) => {
  switch (setting.id) {
    case 2: // 语言设置
      handleLanguageChange()
      break
    case 3: // 清除缓存
      handleClearCache()
      break
    case 4: // 关于应用
      navigateTo('/pages/about/about')
      break
  }
}

// 处理开关变化
const handleSwitchChange = (setting: any, event: any) => {
  if (setting.id === 1) { // 深色模式
    const checked = event.detail.value
    setting.checked = checked
    appStore.setTheme(checked ? 'dark' : 'light')
    showToast(`已${checked ? '开启' : '关闭'}深色模式`)
  }
}

// 处理语言切换
const handleLanguageChange = async () => {
  const confirmed = await showConfirm('是否切换语言？切换后将重启应用')
  if (confirmed) {
    const newLocale = appStore.locale === 'zh-CN' ? 'en-US' : 'zh-CN'
    appStore.setLocale(newLocale)
    
    // 更新设置显示
    const languageSetting = settingList.value.find(item => item.id === 2)
    if (languageSetting) {
      languageSetting.value = newLocale === 'zh-CN' ? '简体中文' : 'English'
    }
    
    showToast('语言设置已更新')
  }
}

// 清除缓存
const handleClearCache = async () => {
  const confirmed = await showConfirm('确定要清除缓存吗？')
  if (confirmed) {
    try {
      uni.clearStorageSync()
      showToast('缓存清除成功', 'success')
    } catch (error) {
      showToast('缓存清除失败')
    }
  }
}

// 登录
const handleLogin = () => {
  navigateTo('/pages/login/login')
}

// 退出登录
const handleLogout = async () => {
  const confirmed = await showConfirm('确定要退出登录吗？')
  if (confirmed) {
    await userStore.logout()
  }
}

onMounted(() => {
  console.log('User page mounted')
})
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #F2F3F5;
}

.status-bar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.user-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px 16px 24px;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 40px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  margin-right: 16px;
}

.user-details {
  flex: 1;
}

.nickname {
  font-size: 20px;
  font-weight: bold;
  color: white;
  margin-bottom: 4px;
}

.username {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.user-stats {
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
}

.stat-value {
  display: block;
  font-size: 16px;
  font-weight: bold;
  color: white;
  margin-bottom: 4px;
}

.stat-label {
  display: block;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

.menu-section {
  background: white;
  margin: 16px 16px 0;
  border-radius: 12px;
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #F2F6FC;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-icon {
  font-size: 20px;
  margin-right: 12px;
}

.menu-content {
  flex: 1;
}

.menu-title {
  display: block;
  font-size: 16px;
  color: #303133;
  margin-bottom: 2px;
}

.menu-desc {
  display: block;
  font-size: 12px;
  color: #909399;
}

.menu-arrow {
  font-size: 14px;
  color: #C0C4CC;
}

.settings-section {
  margin: 16px;
}

.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #909399;
  margin-bottom: 8px;
  margin-left: 4px;
}

.setting-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background: white;
  border-radius: 12px;
  margin-bottom: 8px;
}

.setting-icon {
  font-size: 18px;
  margin-right: 12px;
}

.setting-content {
  flex: 1;
}

.setting-title {
  display: block;
  font-size: 16px;
  color: #303133;
  margin-bottom: 2px;
}

.setting-value {
  display: block;
  font-size: 12px;
  color: #909399;
}

.setting-arrow {
  font-size: 14px;
  color: #C0C4CC;
}

.action-section {
  padding: 24px 16px;
}

.action-button {
  width: 100%;
  height: 48px;
  border-radius: 24px;
  border: none;
  font-size: 16px;
  font-weight: 500;
  background: #FFFFFF;
  color: #303133;
  border: 1px solid #DCDFE6;
}

.action-button.primary {
  background: #409EFF;
  color: white;
  border: none;
}

.safe-area-bottom {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
</style> 